package com.chimm.redpacket.bean;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author Chimm Huang
 */
public class RedPacket implements Serializable {
    /** 红包金额 */
    private BigDecimal amount;
    /** 红包个数 */
    private Integer num;
    /** 剩余红包金额 */
    private BigDecimal remainAmount;
    /** 剩余红包个数 */
    private Integer remainNum;

    public RedPacket(BigDecimal amount, Integer num) {
        this.amount = amount;
        this.remainAmount = amount;
        this.num = num;
        this.remainNum = num;
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    public BigDecimal getRemainAmount() {
        return remainAmount;
    }

    public void setRemainAmount(BigDecimal remainAmount) {
        this.remainAmount = remainAmount;
    }

    public Integer getRemainNum() {
        return remainNum;
    }

    public void setRemainNum(Integer remainNum) {
        this.remainNum = remainNum;
    }

    public List<BigDecimal> splitRedPacket() {
        // 红包的数量
        Integer num = this.getNum();
        // 红包的金额
        BigDecimal remainAmount = this.getRemainAmount();
        //最小金额
        BigDecimal min = BigDecimal.valueOf(0.01);

        Random r = new Random();

        List<BigDecimal> redPacketList = new ArrayList<>();
        for (Integer i = 0; i < num; i++) {

            if (i == num - 1) {
                redPacketList.add(remainAmount);
                break;
            }

            // 红包剩余数量
            int remainNum = num - i;
            //最大金额（开区间）
            BigDecimal max = remainAmount.divide(new BigDecimal(remainNum), 2, RoundingMode.DOWN).multiply(BigDecimal.valueOf(2L));
            //获取随机金额,不超过最大值max
            BigDecimal money = BigDecimal.valueOf(r.nextDouble()).multiply(max);
            // 如果随机金额=0，则取最小的值
            money = money.compareTo(min) <= 0 ? min : money;
            //向下取整后取小数点后2位
            money = money.setScale(2, RoundingMode.DOWN);

            //设置剩余金额
            remainAmount = remainAmount.subtract(money);
            redPacketList.add(money);
        }
        return redPacketList;
    }
}
